package csc.daonjpa.java.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

import csc.daonjpa.java.controller.EntityManagerFactoryUtil;
import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.Card;
import csc.daonjpa.java.domain.Customer;

public class CardDAO {
	public List<Card> getCards(String loginId){
		List<Card> cards = new ArrayList<Card>();
		EntityManager entityManager = EntityManagerFactoryUtil
				.createEntityManager();

		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();

		// -----------Begin transaction-----------
		
		List<Account> accounts = null;
		try {
			entr.begin();
			// Get a list of accounts from DB

			TypedQuery<Customer> query = entityManager.createQuery(
					"SELECT c FROM "
					+ Customer.class.getName()
					
					+ "  c where c.loginId=:id", Customer.class);

			query.setParameter("id", loginId);
			Customer a= query.getSingleResult();
			
			accounts = (List<Account>) a.getAccount();
			for(Account account: accounts){
				String accountNumber = account.getAccountNumber();
				TypedQuery<Card> query1 = entityManager.createQuery(
						"SELECT c FROM "
						+ Card.class.getName()
						
						+ "  c where c.accountNumber=:acNum", Card.class);
				query1.setParameter("acNum", accountNumber);
				Card c = query1.getSingleResult();
				cards.add(c);
			}
				
			
			entr.commit();
		} catch (Exception e) {
			System.out.println(" " + e.getMessage() + "Get all cards of all account of customer");
			entityManager.close();
		}
		return cards;
	}
	
	public boolean addCard(Card card, String accountNumber) {
		EntityManager entityManager = EntityManagerFactoryUtil
				.createEntityManager();
		AccountDAO accDao = new AccountDAO();
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();

		try {
			// -----------Begin transaction-----------
			entr.begin();
			// Insert a row to Account table
			Account account = accDao.getAccountByAccno(accountNumber);
			card.setAccount(account);
			entityManager.persist(card);

			entr.commit();
		} catch (Exception e) {
			System.out.println(" " + e.getMessage() + "Add account");
			entityManager.close();
			return false;
		}
		// -----------End transaction-----------

		return true;
	}

	
}
